<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="role-permission-dialog" v-loading="loading">
      <!-- 角色信息 -->
      <div class="role-info">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="角色名称">{{ role?.name }}</el-descriptions-item>
          <el-descriptions-item label="角色描述">{{ role?.description || '无' }}</el-descriptions-item>
          <el-descriptions-item label="关联用户">
            <el-tag v-if="roleUsers.count > 0" type="info">
              {{ roleUsers.count }} 个用户
            </el-tag>
            <el-tag v-else type="success">无关联用户</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="权限覆盖率">
            <el-progress 
              :percentage="permissionSummary.coverage_percentage" 
              :color="getProgressColor(permissionSummary.coverage_percentage)"
              :stroke-width="8"
            />
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 权限配置标签页 -->
      <el-tabs v-model="activeTab" class="permission-tabs">
        <!-- 菜单权限 -->
        <el-tab-pane label="菜单权限" name="menu">
          <div class="permission-section">
            <div class="section-header">
              <span>菜单访问权限</span>
              <div class="section-actions">
                <el-button size="small" @click="expandAllMenus">展开全部</el-button>
                <el-button size="small" @click="collapseAllMenus">收起全部</el-button>
                <el-button size="small" type="primary" @click="selectAllMenus">全选</el-button>
                <el-button size="small" @click="clearAllMenus">清空</el-button>
              </div>
            </div>
            
            <el-tree
              ref="menuTreeRef"
              :data="menuTreeData"
              :props="treeProps"
              show-checkbox
              node-key="id"
              :default-checked-keys="checkedMenuIds"
              :check-strictly="false"
              @check="handleMenuCheck"
              class="permission-tree"
            >
              <template #default="{ node, data }">
                <div class="tree-node">
                  <el-icon v-if="data.icon" class="node-icon">
                    <component :is="data.icon" />
                  </el-icon>
                  <span class="node-label">{{ data.name }}</span>
                  <el-tag v-if="data.level === 1" size="small" type="primary">{{ data.level }}级菜单</el-tag>
                  <el-tag v-else-if="data.level === 2" size="small" type="success">{{ data.level }}级菜单</el-tag>
                </div>
              </template>
            </el-tree>
          </div>
        </el-tab-pane>

        <!-- 权限统计 -->
        <el-tab-pane label="权限统计" name="summary">
          <div class="permission-section">
            <div class="section-header">
              <span>权限配置概览</span>
            </div>

            <div class="permission-summary">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-card>
                    <template #header>
                      <span>菜单权限</span>
                    </template>
                    <div class="summary-item">
                      <div class="summary-number">{{ permissionSummary.assigned_menus }}/{{ permissionSummary.total_menus }}</div>
                      <div class="summary-label">已分配菜单</div>
                      <el-progress
                        :percentage="Math.round((permissionSummary.assigned_menus / permissionSummary.total_menus) * 100)"
                        :color="getProgressColor(Math.round((permissionSummary.assigned_menus / permissionSummary.total_menus) * 100))"
                      />
                    </div>
                  </el-card>
                </el-col>
                <el-col :span="12">
                  <el-card>
                    <template #header>
                      <span>整体覆盖率</span>
                    </template>
                    <div class="summary-item">
                      <div class="summary-number">{{ permissionSummary.coverage_percentage }}%</div>
                      <div class="summary-label">权限覆盖率</div>
                      <el-progress
                        :percentage="permissionSummary.coverage_percentage"
                        :color="getProgressColor(permissionSummary.coverage_percentage)"
                      />
                    </div>
                  </el-card>
                </el-col>
              </el-row>

              <div class="summary-description">
                <el-alert
                  title="权限说明"
                  type="info"
                  :closable="false"
                  show-icon
                >
                  <p>当前系统基于菜单权限进行访问控制。用户只能访问其角色被分配的菜单页面。</p>
                  <p>建议为每个角色分配适当的菜单权限，遵循最小权限原则。</p>
                </el-alert>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- 关联用户 -->
        <el-tab-pane label="关联用户" name="users">
          <div class="users-section">
            <div class="section-header">
              <div class="header-left">
                <span>使用该角色的用户 ({{ roleUsers.count }})</span>
              </div>
              <div class="header-right">
                <el-button type="primary" size="small" @click="showAddUserDialog = true">
                  <el-icon><Plus /></el-icon>
                  添加用户
                </el-button>
                <el-button
                  v-if="selectedUsers.length > 0"
                  type="danger"
                  size="small"
                  @click="batchRemoveUsers"
                >
                  <el-icon><Delete /></el-icon>
                  移除选中 ({{ selectedUsers.length }})
                </el-button>
              </div>
            </div>

            <el-table
              :data="roleUsers.users"
              style="width: 100%"
              max-height="300"
              @selection-change="handleUserSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="username" label="用户名">
                <template #default="{ row }">
                  <UserDisplay :user="row" />
                </template>
              </el-table-column>
              <el-table-column prop="email" label="邮箱" />
              <el-table-column prop="is_active" label="状态" width="80">
                <template #default="{ row }">
                  <el-tag :type="row.is_active ? 'success' : 'danger'" size="small">
                    {{ row.is_active ? '激活' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="{ row }">
                  <el-button
                    size="small"
                    type="danger"
                    link
                    @click="removeUser(row)"
                  >
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-empty v-if="roleUsers.count === 0" description="暂无关联用户" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="savePermissions" :loading="saving">
          保存权限配置
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 添加用户对话框 -->
  <el-dialog
    v-model="showAddUserDialog"
    title="添加用户到角色"
    width="600px"
    :close-on-click-modal="false"
  >
    <div class="add-user-dialog">
      <!-- 搜索框 -->
      <div class="search-section">
        <el-input
          v-model="userSearchKeyword"
          placeholder="搜索用户名或邮箱"
          @input="searchUsers"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 可添加的用户列表 -->
      <div class="available-users">
        <el-table
          :data="availableUsers"
          style="width: 100%"
          max-height="300"
          @selection-change="handleAvailableUsersSelection"
          v-loading="loadingUsers"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="username" label="用户名" width="120">
            <template #default="{ row }">
              <UserDisplay :user="row" />
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱" />
          <el-table-column label="姓名" width="100">
            <template #default="{ row }">
              {{ getFullName(row) }}
            </template>
          </el-table-column>
          <el-table-column prop="is_active" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.is_active ? 'success' : 'danger'" size="small">
                {{ row.is_active ? '激活' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="showAddUserDialog = false">取消</el-button>
        <el-button
          type="primary"
          @click="confirmAddUsers"
          :disabled="selectedAvailableUsers.length === 0"
          :loading="addingUsers"
        >
          添加选中用户 ({{ selectedAvailableUsers.length }})
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Search } from '@element-plus/icons-vue'
import { userManagementAPI } from '@/api/userManagement'
import UserDisplay from '@/components/UserDisplay.vue'
import { getFullName } from '@/utils/userUtils'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  role: {
    type: Object,
    default: null
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'saved'])

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const activeTab = ref('menu')
const menuTreeRef = ref(null)

const roleUsers = ref({ users: [], count: 0 })
const permissionSummary = ref({
  total_menus: 0,
  assigned_menus: 0,
  total_permissions: 0,
  assigned_permissions: 0,
  coverage_percentage: 0
})

const menuTreeData = ref([])
const checkedMenuIds = ref([])

// 用户管理相关数据
const showAddUserDialog = ref(false)
const userSearchKeyword = ref('')
const availableUsers = ref([])
const selectedUsers = ref([])
const selectedAvailableUsers = ref([])
const loadingUsers = ref(false)
const addingUsers = ref(false)

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const dialogTitle = computed(() => {
  if (!props.role) return '权限管理'
  return `角色权限管理 - ${props.role.name}`
})

const treeProps = {
  children: 'children',
  label: 'name'
}

// 方法
const loadRoleData = async () => {
  if (!props.role) return
  
  loading.value = true
  try {
    // 并行加载数据
    const [usersResponse, permissionsResponse, menusResponse] = await Promise.all([
      userManagementAPI.getRoleUsers(props.role.id),
      userManagementAPI.getRolePermissionsDetail(props.role.id),
      userManagementAPI.getAllMenus()
    ])

    roleUsers.value = usersResponse
    permissionSummary.value = permissionsResponse.summary
    
    // 处理菜单数据
    menuTreeData.value = buildMenuTree(menusResponse.results || menusResponse)
    
    // 设置已选中的菜单
    checkedMenuIds.value = permissionsResponse.menu_permissions.map(mp => mp.menu)

    // 在下一个tick中设置树形组件的选中状态
    await nextTick()
    if (menuTreeRef.value && checkedMenuIds.value.length > 0) {
      menuTreeRef.value.setCheckedKeys(checkedMenuIds.value)
    }
    
  } catch (error) {
    console.error('加载角色数据失败:', error)
    ElMessage.error('加载角色数据失败')
  } finally {
    loading.value = false
  }
}

const buildMenuTree = (menus) => {
  // 构建菜单树结构
  const menuMap = new Map()
  const rootMenus = []
  
  // 先创建所有菜单节点
  menus.forEach(menu => {
    menuMap.set(menu.id, {
      ...menu,
      children: []
    })
  })
  
  // 构建树结构
  menus.forEach(menu => {
    const menuNode = menuMap.get(menu.id)
    if (menu.parent) {
      const parent = menuMap.get(menu.parent)
      if (parent) {
        parent.children.push(menuNode)
      }
    } else {
      rootMenus.push(menuNode)
    }
  })
  
  return rootMenus
}



const getProgressColor = (percentage) => {
  if (percentage < 30) return '#f56c6c'
  if (percentage < 70) return '#e6a23c'
  return '#67c23a'
}

// 菜单操作方法
const expandAllMenus = () => {
  // 展开所有菜单节点
  if (menuTreeRef.value) {
    const allKeys = getAllMenuKeys(menuTreeData.value)
    allKeys.forEach(key => {
      menuTreeRef.value.store.nodesMap[key]?.expand()
    })
  }
}

const collapseAllMenus = () => {
  // 收起所有菜单节点
  if (menuTreeRef.value) {
    const allKeys = getAllMenuKeys(menuTreeData.value)
    allKeys.forEach(key => {
      menuTreeRef.value.store.nodesMap[key]?.collapse()
    })
  }
}

const selectAllMenus = () => {
  if (menuTreeRef.value) {
    const allKeys = getAllMenuKeys(menuTreeData.value)
    menuTreeRef.value.setCheckedKeys(allKeys)
  }
}

const clearAllMenus = () => {
  if (menuTreeRef.value) {
    menuTreeRef.value.setCheckedKeys([])
  }
}

const getAllMenuKeys = (menus) => {
  let keys = []
  menus.forEach(menu => {
    keys.push(menu.id)
    if (menu.children && menu.children.length > 0) {
      keys = keys.concat(getAllMenuKeys(menu.children))
    }
  })
  return keys
}

const handleMenuCheck = (data, checked) => {
  // 菜单选择变化处理
  console.log('菜单选择变化:', data, checked)
}



const savePermissions = async () => {
  if (!props.role) return

  saving.value = true
  try {
    // 获取选中的菜单ID
    const checkedMenus = menuTreeRef.value.getCheckedKeys()

    // 保存菜单权限
    await userManagementAPI.assignMenusToRole(props.role.id, {
      menu_ids: checkedMenus
    })

    ElMessage.success('菜单权限配置保存成功')
    emit('saved')
    handleClose()

  } catch (error) {
    console.error('保存权限配置失败:', error)
    ElMessage.error('保存权限配置失败')
  } finally {
    saving.value = false
  }
}

const handleClose = () => {
  visible.value = false
  activeTab.value = 'menu'
}

// 用户管理方法
const handleUserSelectionChange = (selection) => {
  selectedUsers.value = selection
}

const handleAvailableUsersSelection = (selection) => {
  selectedAvailableUsers.value = selection
}

const searchUsers = async () => {
  if (!props.role) return

  loadingUsers.value = true
  try {
    // 获取所有用户
    const allUsersResponse = await userManagementAPI.getUsers({
      search: userSearchKeyword.value
    })

    // 过滤掉已经关联的用户
    const currentUserIds = roleUsers.value.users.map(user => user.id)
    availableUsers.value = (allUsersResponse.results || allUsersResponse).filter(
      user => !currentUserIds.includes(user.id)
    )

  } catch (error) {
    console.error('搜索用户失败:', error)
    ElMessage.error('搜索用户失败')
  } finally {
    loadingUsers.value = false
  }
}

const confirmAddUsers = async () => {
  if (selectedAvailableUsers.value.length === 0) return

  addingUsers.value = true
  try {
    // 为选中的用户分配角色
    for (const user of selectedAvailableUsers.value) {
      const currentRoleIds = (user.roles || []).map(role => typeof role === 'object' ? role.id : role)
      const updatedRoleIds = [...currentRoleIds, props.role.id]

      await userManagementAPI.updateUser(user.id, {
        role_ids: updatedRoleIds  // 后端需要 role_ids 字段
      })
    }

    ElMessage.success(`成功添加 ${selectedAvailableUsers.value.length} 个用户`)
    showAddUserDialog.value = false
    selectedAvailableUsers.value = []
    userSearchKeyword.value = ''
    availableUsers.value = []

    // 重新加载角色数据
    await loadRoleData()

  } catch (error) {
    console.error('添加用户失败:', error)
    ElMessage.error('添加用户失败')
  } finally {
    addingUsers.value = false
  }
}

const removeUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要将用户 "${user.username}" 从角色 "${props.role.name}" 中移除吗？`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 从用户的角色列表中移除当前角色
    const currentRoleIds = (user.roles || []).map(role => typeof role === 'object' ? role.id : role)
    const updatedRoleIds = currentRoleIds.filter(roleId => roleId !== props.role.id)

    await userManagementAPI.updateUser(user.id, {
      role_ids: updatedRoleIds
    })

    ElMessage.success('用户移除成功')
    await loadRoleData()

  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除用户失败:', error)
      console.error('错误详情:', error.response?.data)
      ElMessage.error(`移除用户失败: ${error.response?.data?.detail || error.message}`)
    }
  }
}

const batchRemoveUsers = async () => {
  if (selectedUsers.value.length === 0) return

  try {
    await ElMessageBox.confirm(
      `确定要将选中的 ${selectedUsers.value.length} 个用户从角色 "${props.role.name}" 中移除吗？`,
      '确认批量移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 批量移除用户
    for (const user of selectedUsers.value) {
      const currentRoleIds = (user.roles || []).map(role => typeof role === 'object' ? role.id : role)
      const updatedRoleIds = currentRoleIds.filter(roleId => roleId !== props.role.id)

      await userManagementAPI.updateUser(user.id, {
        role_ids: updatedRoleIds  // 后端需要 role_ids 字段
      })
    }

    ElMessage.success(`成功移除 ${selectedUsers.value.length} 个用户`)
    selectedUsers.value = []
    await loadRoleData()

  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量移除用户失败:', error)
      ElMessage.error('批量移除用户失败')
    }
  }
}

// 监听角色变化
watch(() => props.role, (newRole) => {
  if (newRole && visible.value) {
    loadRoleData()
  }
}, { immediate: true })

watch(visible, (newVisible) => {
  if (newVisible && props.role) {
    loadRoleData()
  }
})

watch(showAddUserDialog, (newVisible) => {
  if (newVisible) {
    searchUsers()
  }
})
</script>

<style scoped>
.role-permission-dialog {
  max-height: 600px;
  overflow-y: auto;
}

.role-info {
  margin-bottom: 20px;
}

.permission-tabs {
  margin-top: 20px;
}

.permission-section {
  padding: 10px 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.header-left {
  flex: 1;
}

.header-right {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

.section-actions {
  display: flex;
  gap: 8px;
}

.permission-tree {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.node-icon {
  color: #409eff;
}

.node-label {
  flex: 1;
}

.function-permissions {
  max-height: 400px;
  overflow-y: auto;
}

.module-section {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  background-color: #fafafa;
}

.module-title {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.permissions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 10px;
}

.permission-item {
  display: flex;
  align-items: center;
  padding: 8px;
  background-color: white;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.users-section {
  padding: 10px 0;
}

.permission-summary {
  padding: 20px 0;
}

.summary-item {
  text-align: center;
  padding: 20px;
}

.summary-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #303133;
}

.summary-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 15px;
}

.summary-description {
  margin-top: 30px;
}

.add-user-dialog {
  padding: 10px 0;
}

.search-section {
  margin-bottom: 15px;
}

.available-users {
  margin-top: 15px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
